﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.Iservice;
using ZSZ.Service.Entity;

namespace ZSZ.Service
{
    public class AttachmentService : IAttachmentService
    {
        private AttachmentDTO ToDto(AttachmentEntity e) {
            AttachmentDTO dto = new AttachmentDTO();
            dto.CreateTime = e.CreateDatatime;
            dto.IconName = e.IconName;
            dto.Id = e.Id;
            dto.Name = e.Name;
            return dto;
        }
        public AttachmentDTO[] GetAll()
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<AttachmentEntity> cs = new CommonService<AttachmentEntity>(ct);
                List<AttachmentDTO> dtps = new List<AttachmentDTO>();
                foreach (var item in cs.GetAll())
                {
                    dtps.Add(ToDto(item));
                }
                return dtps.ToArray();
            }
        }

        public AttachmentDTO[] GetByHouseId(long houseId)
        {

            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<HouseEntity> cs = new CommonService<HouseEntity>(ct);
               var house= cs.GetAll().Include(h => h.Attachments).SingleOrDefault(h => h.Id == houseId);
                if (house==null)
                {
                    throw new ArgumentException("没有这个房子");
                }
                List<AttachmentDTO> ads = new List<AttachmentDTO>();
                foreach (var item in house.Attachments)
                {
                    ads.Add(ToDto(item));
                }
                return ads.ToArray();
            }
        }
        public long AddNew(string IconName, string name)
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<AttachmentEntity> cs = new CommonService<AttachmentEntity>(ct);
               bool exits = cs.GetAll().Any(s=>s.Name==name);
                if (exits)
                {
                    throw new ArgumentException("已经存在这个房屋配置了");
                }
                AttachmentEntity en = new AttachmentEntity();
                en.IconName = IconName;
                en.Name = name;
                ct.Attachments.Add(en);
                ct.SaveChanges();
                return en.Id;
            }
        }
    }
}
